const express = require('express');
const router = express.Router();
const FileData = require("../data/FileData");

const PW = require("png-word");
const pw = new PW();
// var randomWord = require("../public/javascripts/random-number");
const R = require("random-word");
var r = R(["123456"]);

/* GET users listing. */

router.post('/post-review', async (req, res) => {
  const reviewContent = req.body["post-review"];
  await FileData.writeReviewFile("./data/reviews.json", req.session.user, reviewContent);
  console.log("成功写入留言");
  req.session.save(() => {
    res.redirect("back");
  });
});

router.post('/login', async (req, res) => {
  const {loginname, psd, vnum} = req.body;
  let users = await FileData.readUserFile("./data/users.json");
  if (!users) {
    console.log("----");
    req.session.save(()=> {
      res.redirect("back");
    });
  } else {
    if (
      req.session.firstnum + req.session.secondnum === Number(vnum) &&
      users[loginname] && users[loginname].password === psd) {
        req.session.user = loginname;
        console.log(loginname + " 登录成功!");
        req.session.save(()=> {
          res.redirect("back");
        });
    }
    else {
      console.log(req.session.firstnum, req.session.secondnum, vnum);
      req.session.save(()=> {
        res.redirect("back");
      });
    }
  }
});

router.get("/logout", (req, res) => {
  req.session.user = undefined;
  req.session.save(() => {
    res.redirect("back");
  });
});

router.post('/reg', async (req, res) => {
  const {regname, password, confirm, vimg} = req.body;
  if (
    req.session.vimg === vimg &&
    regname && password === confirm
  ) {
    console.log("注册成功!");
    await FileData.writeUserFile("./data/users.json", regname, password, "password");
    console.log("成功写入users.json文件中!");
  }
  console.log(req.session.vimg, vimg);
  req.session.save(() => {
    res.redirect("back");
  });
});

router.get('/vimg', (req, res) => {
  let randomNum = r.random(4);
  req.session.vimg = randomNum;
  // req.session.vimg = randomWord(4);
  pw.createReadStream(req.session.vimg).pipe(res);
});

module.exports = router;
